package com.zp.datax.core;

import lombok.Setter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 结果过虑器
 *
 * @author bruce
 * @date 2019-07-15
 */
@Setter
public class ResultFilterHandler implements Handler {

    private Handler handler;

    private final static Pattern PATTERN_READ_RECORD = Pattern.compile("^\"record\"\\s*:\\s*(\\d+)$");
    private final static Pattern PATTERN_READ_PERCENTAGE = Pattern.compile("^\"percentage\":(\\d+\\.*\\d*)$");
    private final static Pattern PATTERN_READ_TOTAL = Pattern.compile("^读出记录总数\\s+:\\s+(\\d+)$");
    private final static Pattern PATTERN_READ_FAIL_COUNT = Pattern.compile("^读写失败总数\\s+:\\s+(\\d+)$");


    @Override
    public Object[] handler(String str) {

        return readRecord(str);
    }

    private Object[] readRecord(String str) {
        Matcher matcher = matcher(PATTERN_READ_RECORD, str.trim());
        if (matcher.matches()) {
            return new String[]{"record", matcher.group(1)};
        }

        return readPercentage(str);
    }

    private Object[] readPercentage(String str) {
        Matcher matcher = matcher(PATTERN_READ_PERCENTAGE, str.trim());
        if (matcher.matches()) {
            return new String[]{"percentage", matcher.group(1)};
        }

        return readTotal(str);
    }

    private Object[] readTotal(String str) {
        Matcher matcher = matcher(PATTERN_READ_TOTAL, str.trim());
        if (matcher.matches()) {
            return new String[]{"total", matcher.group(1)};
        }

        return readFailCount(str);
    }

    private Object[] readFailCount(String str) {
        Matcher matcher = matcher(PATTERN_READ_FAIL_COUNT, str.trim());
        if (matcher.matches()) {
            return new String[]{"failCount", matcher.group(1)};
        }
        return handler(handler, str);
    }


}
